<template>
  <div class="page-bg">
    <listTable
      ref="tableRef"
      v-model="tableData"
      :isCheck="false"
      @getList="getList"
      :pageSizes="[100]"
    >
      <template #action>
        <el-button @click="showFun()" type="primary">新增角色</el-button>
      </template>
      <el-table-column prop="id" label="ID" width="100" align="center" />
      <el-table-column prop="name" label="名称" />
      <el-table-column
        align="center"
        width="100"
        label="状态"
        :filters="[
          { text: '启用', value: '1' },
          { text: '禁用', value: '0' },
        ]"
        :filter-method="filterTag"
        filter-placement="bottom-end"
      >
        <template #default="scope">
          <el-tag v-if="scope.row.a_show == '1'" type="success">启用</el-tag>
          <el-tag v-else type="info">禁用</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="sort" label="排序" width="100" align="center" />
      <el-table-column
        prop="up_time"
        label="更新时间"
        width="180"
        align="center"
      />
      <el-table-column
        prop="create_time"
        label="创建时间"
        width="180"
        align="center"
      />
      <el-table-column fixed="right" label="操作栏" width="180" align="center">
        <template #default="scope">
          <el-button
            link
            type="primary"
            size="small"
            @click="showTreeFun(scope.row)"
            >分配权限</el-button
          >
          <el-button
            link
            type="primary"
            size="small"
            @click="showFun(scope.row)"
            >编辑</el-button
          >
          <el-popconfirm title="确定删除？" @confirm="delFn(scope.row)">
            <template #reference>
              <el-button link type="primary" size="small">删除</el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </listTable>

    <!-- 表单弹窗 -->
    <el-dialog
      v-model="layerForm.show"
      :title="layerForm.form.id ? '编辑角色' : '新增角色'"
      width="380px"
    >
      <div class="edit-role">
        <el-form label-position="top" label-width="100px">
          <el-form-item label="角色名称：">
            <el-input
              v-model.trim="layerForm.form.name"
              placeholder="请输入角色"
            ></el-input>
          </el-form-item>
          <el-form-item label="状态：">
            <el-radio v-model="layerForm.form.a_show" label="1">
              启用
            </el-radio>
            <el-radio v-model="layerForm.form.a_show" label="0">
              禁用
            </el-radio>
          </el-form-item>
        </el-form>
        <div class="lfex">
          <el-button size="large" @click="layerForm.show = false"
            >取消</el-button
          >
          <el-button size="large" type="primary" @click="subForm"
            >确定</el-button
          >
        </div>
      </div>
    </el-dialog>

    <!-- 分配角色权限 -->
    <el-drawer v-model="layerTree.show" direction="rtl">
      <template #header>
        <h4>分配权限</h4>
      </template>
      <template #default>
        <div>
          <el-tree
            :data="layerTree.tree"
            show-checkbox
            node-key="id"
            default-expand-all
            :props="defaultProps"
            ref="treeRef"
            check-strictly
          />
        </div>
      </template>
      <template #footer>
        <div style="flex: auto">
          <el-button @click="layerTree.show = false">取消</el-button>
          <el-button type="primary" @click="subTreeForm">保存</el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>

<script lang="ts" setup>
import { listTable, typeColumn } from "@/components/listPage";
import { ElMessage } from "element-plus";
import {
  tableDataType,
  typeItem,
  typeItemTypeName,
  tableDataQuery,
} from "@/common/interface";
import { post } from "@/common/http";
import dayjs from "dayjs";
import { useSysStore } from "@/store/sys";
import { build_tree } from "@/common/tool";

const typeStr = typeItemTypeName.role;

const tableRef = ref();

//表格组件数据
const tableData = reactive<tableDataType<typeItem>>(new tableDataType());

//获取列表
function getList(data: tableDataQuery): void {
  post("api/Type/type_list_data", {
    page: data.page,
    limit: data.limit,
    type: typeStr,
  }).then((res) => {
    tableData.lists = res.data.map((v: typeItem) => {
      return {
        ...v,
        up_time: dayjs(Number(v.up_time) * 1000).format("YYYY-MM-DD HH:mm:ss"),
        create_time: dayjs(Number(v.create_time) * 1000).format(
          "YYYY-MM-DD HH:mm:ss"
        ),
      };
    });
    tableData.total = res.total ?? 0;
    tableData.loading = false;
  });
}

//删除 / 批量删除
function delFn(item: typeItem) {
  post("api/Type/type_del_data", { id: item.id, name: item.name }).then(() =>
    tableRef.value.reload()
  );
}

//筛选当前页数据的 状态
const filterTag = (value: string, row: typeItem) => {
  return row.a_show === value;
};

//编辑
const layerForm = reactive({
  show: false,
  form: new typeItem(typeStr),
});
function showFun(data?: typeItem) {
  if (data) {
    layerForm.form = JSON.parse(JSON.stringify(toRaw(data)));
  } else {
    layerForm.form = new typeItem(typeStr);
  }
  layerForm.show = true;
}

function subForm() {
  let data = toRaw(layerForm.form);
  if (!data.name) return ElMessage.error("请输入角色名称");
  data.other = layerTree.list[0].id; //新建角色，默认给一个首页的权限
  post("api/Type/editType", data).then((res) => {
    tableRef.value.reload();
    ElMessage.success(res.msg);
    layerForm.show = false;
  });
}

//权限分配
const defaultProps = {
  children: "children",
  label: "name",
};

onMounted(() => {
  post("api/Admin/getNode", {
    prop: "id", //需要排序的字段
    sort: "desc", //desc asc
  }).then((res) => {
    res.data.list[0].disabled = true;
    layerTree.list = res.data.list;
    layerTree.tree = build_tree(res.data.list, 0);
  });
});

const treeRef = ref();
const layerTree = reactive<any>({
  show: false,
  tree: [],
  list: [],
  form: new typeItem(typeStr),
});

function showTreeFun(data?: typeItem) {
  layerTree.form = JSON.parse(JSON.stringify(toRaw(data)));
  layerTree.show = true;
  nextTick(() => {
    treeRef.value.setCheckedKeys(layerTree.form.other.split(","));
  });
}

function subTreeForm() {
  let data = toRaw(layerTree.form);
  post("api/Type/editType", {
    ...data,
    other: treeRef.value.getCheckedKeys().toString(),
  }).then((res) => {
    tableRef.value.reload();
    ElMessage.success(res.msg);
    layerTree.show = false;
  });
}
</script>

<style lang="scss" scoped>
.edit-role {
  padding: 0 10px 10px;
}
:deep(.el-drawer__header) {
  margin-bottom: 20px;
}
:deep(.el-drawer__body) {
  padding-top: 0;
}
</style>
